package com.my.test;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import java.io.*;

public class Tar {

    private static void tarFile(File file, TarArchiveOutputStream taos) throws Exception {

        TarArchiveEntry tae = new TarArchiveEntry(file);
        tae.setSize(file.length());//大小
        tae.setName(new String(file.getName().getBytes("gbk"), "ISO-8859-1"));//不设置会默认全路径
        taos.putArchiveEntry(tae);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int count;
        byte data[] = new byte[1024];
        while ((count = bis.read(data, 0, 1024)) != -1) {
            taos.write(data, 0, count);
        }
        bis.close();

        taos.closeArchiveEntry();

    }

    private static void tarDir(File file, TarArchiveOutputStream taos) throws Exception {

        {

            TarArchiveEntry tae = new TarArchiveEntry(file);
            //tae.setName(new String((file.getName()+File.separator).getBytes("gbk"), "ISO-8859-1"));//不设置会默认全路径
            taos.putArchiveEntry(tae);


        }



        File[] files = file.listFiles();
        for (File file1:files){
            TarArchiveEntry tae = new TarArchiveEntry(file1);
            //tae.setSize(file1.length());//大小
            //tae.setName(new String((file.getName()+File.separator+file1.getName()).getBytes("gbk"), "ISO-8859-1"));//不设置会默认全路径
            taos.putArchiveEntry(tae);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
            int count;
            byte data[] = new byte[1024];
            while ((count = bis.read(data, 0, 1024)) != -1) {
                taos.write(data, 0, count);
            }
            bis.close();


        }


        taos.closeArchiveEntry();

    }

    public static void main(String[] args) throws Exception {

        /*OutputStream outputStream = new FileOutputStream("D:/readme.tar");
        TarArchiveOutputStream taos = new TarArchiveOutputStream(outputStream);
        File file = new File("D:/readme.txt");
        tarFile(file,taos);*/

        OutputStream outputStream = new FileOutputStream("D:/test.tar");
        TarArchiveOutputStream taos = new TarArchiveOutputStream(outputStream);
        File file = new File("D:/test");
        tarDir(file,taos);

    }
}
